package com.easy.service.impl;

import com.easy.annotation.LogMethod;
import com.easy.bean.User;
import com.easy.mapper.UserMapper;
import com.easy.service.LoginService;
import com.easy.util.ImageUtil;
import com.easy.util.PasswordUtil;
import com.easy.util.SYS;
import com.easy.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserMapper userMapper;

    @Override
    @LogMethod(serviceName = "用户登录", recordParam = true, recordReturn = true)
    public String login(User user) {
        //登录逻辑
        //1、通过电话查询数据库
        User result = userMapper.getByPhone(user.getPhone());
        if(result == null){
            throw  new RuntimeException("登录异常");
        }
        //2、验证密码
        String password = user.getPassword();
        String encryptionPassword = result.getPassword();
        if(!PasswordUtil.checkPassword(password,encryptionPassword)){
            throw new RuntimeException("登陆异常");
        }
        //3、返回结果token
        String token = TokenUtil.getToken(result.getId(), SYS.REGULAR_USER);
        return token;
    }

    @Override
    public User getById(String token) {
        Object option = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
        Integer userId = Integer.valueOf(option.toString());
        return userMapper.one(userId);
    }

    @Override
    @LogMethod(serviceName = "图片上传", recordParam = true, recordReturn = true)
    public String imgUp(MultipartFile file){
        String newFileName = null;
        try {
            newFileName = ImageUtil.upload(file);
            System.out.println(newFileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return newFileName;
    }






}
